import datetime
import model
import utility
import config

from google.appengine.ext import db
from google.appengine.ext import webapp
from imageprocess import SiteImage 


class CronJob(webapp.RequestHandler):
    def get(self):
        jobs = db.GqlQuery("SELECT * FROM SearchResult WHERE displayimageset = False ") #and query = 'AAPL stock'
        results = jobs.fetch(1)
        for item in results:            
            # select image from image list
            siteurl = '#'
            if item.images is None or len(item.images) == 0:
                rimages = []
                if item.clickurl.find(';') > 0:
                    rimages = []
                else:
                    rimages = utility.html2imgs(item.clickurl)
                item.images = rimages
            images = item.images        
            if item.displayimageindex < len(images):
                eachimage = images[item.displayimageindex]
                if len(eachimage) < 500:
                    sw = item.displayimagewidth
                    sh = item.displayimageheight
                    siteimage = SiteImage()
                    siteimage.set(eachimage)
                    if siteimage.IsDownloaded is False:
                        item.displayimageindex += 1
                        continue
                    if (sw < siteimage.getWidth() and sh < siteimage.getHeight()) and siteimage.IsAdvers() is False:
                        item.displayimageurl = siteimage.getUrl()
                        item.displayimagewidth = siteimage.getWidth()
                        item.displayimageheight = siteimage.getHeight()
                item.displayimageindex += 1

            if item.displayimageindex == len(images):
                item.displayimageset = True
            item.put()
            self.response.out.write('<html><head><script>function reload(){ document.location = ')
            self.response.out.write("'/cron?time=' + new Date().getTime() } setTimeout('reload()', 1000); </script>")
            self.response.out.write('</head><body></body></html>')

